/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkFile, ts, AstTreeUtils } from "arkanalyzer";
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from "../BaseChecker";
import { FileMatcher, MatcherCallback, MatcherTypes } from '../../Index';
import { Defects, IssueReport } from "../../model/Defects";
import { Rule } from "../../model/Rule";
import { RuleListUtil } from "../../utils/common/DefectsList";
import { RuleFix } from '../../model/Fix';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'NoUnnecessaryConditionCheck');
const gMetaData: BaseMetaData = {
    severity: 1,
    ruleDocPath: "docs/no-unnecessary-condition-check.md",
    description: "Disallow conditionals where the type is always truthy or always falsy.",
};

interface Options {
    allowConstantLoopConditions?: boolean;
    allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;
}

interface LocationInfo {
    fileName: string;
    line: number;
    startCol: number;
    endCol: number;
    start: number;
    end: number;
    nameStr: string;
    description: string;
    messageId: MessageId;
}

// 定义消息类型
type MessageId =
    | 'alwaysFalsy'
    | 'alwaysFalsyFunc'
    | 'alwaysNullish'
    | 'alwaysTruthy'
    | 'alwaysTruthyFunc'
    | 'literalBooleanExpression'
    | 'never'
    | 'neverNullish'
    | 'neverOptionalChain'
    | 'noOverlapBooleanExpression'
    | 'noStrictNullCheck';

export class NoUnnecessaryConditionCheck implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private defaultOptions: Options = {
        allowConstantLoopConditions: false,
        allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
    };

    private fileMatcher: FileMatcher = {
        matcherType: MatcherTypes.FILE,
    };

    public registerMatchers(): MatcherCallback[] {
        const fileMatcherCb: MatcherCallback = {
            matcher: this.fileMatcher,
            callback: this.check
        };
        return [fileMatcherCb];
    }

    public check = (arkFile: ArkFile) => {
        if (arkFile instanceof ArkFile) {
            const code = arkFile.getCode();
            if (!code) {
                return;
            }
            const filePath = arkFile.getFilePath();
            const asRoot = AstTreeUtils.getASTNode(arkFile.getName(), code);

            // 检查类型断言
            const locationInfos = this.checkCondition(asRoot, filePath);

            // 输出结果
            locationInfos.forEach(loc => {
                this.addIssueReportNodeFix(loc, filePath);
            });
        }
    }

    private checkCondition(sourceFile: ts.SourceFile, filePath: string): LocationInfo[] {
        const options: Options = this.rule && this.rule.option[0] ? this.rule.option[0] as Options : this.defaultOptions;
        const results: LocationInfo[] = [];
        const visit = (node: ts.Node) => {
            // 直接检查二元表达式 - 这确保我们能捕获所有二元表达式，无论上下文
            if (ts.isBinaryExpression(node)) {
                this.checkBinaryExpression(node, sourceFile, results);
            }
            // 原有的其他条件检查逻辑
            let condition: ts.Expression | undefined;
            if (ts.isIfStatement(node)) {
                // 检查 if 语句的条件
                condition = node.expression;
                this.checkConditionIfStatement(node, condition, sourceFile, results);
            } else if (ts.isWhileStatement(node) && !options.allowConstantLoopConditions) {
                condition = node.expression;
                this.checkConditionWhileStatement(condition, sourceFile, results);
            } else if (ts.isDoStatement(node) && !options.allowConstantLoopConditions) {
                condition = node.expression;
                this.checkIsBinaryExpression(condition, sourceFile, results);
            } else if (ts.isForStatement(node) && !options.allowConstantLoopConditions) {
                condition = node.condition;
                this.checkConditionForStatement(condition, sourceFile, results);
            } else if (ts.isConditionalExpression(node)) {
                condition = node.condition;
                this.checkIsBinaryExpression(condition, sourceFile, results);
            } else if (ts.isOptionalChain(node)) {
                condition = node.expression;
                if (condition) {
                    this.handleGeneralCondition(condition, sourceFile, node, results);
                }
            } else if (ts.isCallExpression(node)) {
                condition = undefined;
                this.handleCallExpression(node, sourceFile, results);
            } else if (ts.isBinaryExpression(node)) {
                condition = undefined;
                this.handleBinaryExpression(node, sourceFile, results, options);
            }
            if (condition) {
                this.checkNode(condition, sourceFile, results);
            }
            // 递归遍历子节点
            ts.forEachChild(node, visit);
        };
        visit(sourceFile);
        return results;
    }

    private checkConditionForStatement(condition: ts.Expression | undefined, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        // 检查赋值操作符在 for 循环条件语句中的使用
        if (condition) {
            this.checkIsBinaryExpression(condition, sourceFile, results);
        }
    }
    private checkConditionWhileStatement(condition: ts.Expression, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        this.checkIsBinaryExpression(condition, sourceFile, results);
        // 处理括号内的赋值表达式((x = 0)) { }
        if (ts.isParenthesizedExpression(condition)) {
            const innerExpression = condition.expression;
            this.checkIsBinaryExpression(innerExpression, sourceFile, results);
        }
    }

    private checkConditionIfStatement(node: ts.IfStatement, condition: ts.Expression, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        this.checkIsBinaryExpression(condition, sourceFile, results);
        this.handleIfStatement(condition, sourceFile, results);
        // 递归检查所有 else if 分支
        let currentNode = node;
        while (currentNode.elseStatement && ts.isIfStatement(currentNode.elseStatement)) {
            const elseIfCondition = currentNode.elseStatement.expression;

            this.checkIsBinaryExpression(elseIfCondition, sourceFile, results);

            // 对 else if 条件执行同样的检查
            this.handleIfStatement(elseIfCondition, sourceFile, results);
            currentNode = currentNode.elseStatement;
        }
    }
    private checkIsBinaryExpression(condition: ts.Expression, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        // 检查赋值操作符在三元条件表达式中的使用
        if (ts.isBinaryExpression(condition) &&
            condition.operatorToken.kind === ts.SyntaxKind.EqualsToken) {

            const rightValue = condition.right;
            const isAlwaysFalsy = this.isAlwaysFalsyValue(rightValue);

            this.reportIssue(
                condition,
                sourceFile,
                isAlwaysFalsy ? 'alwaysFalsy' : 'alwaysTruthy',
                isAlwaysFalsy ?
                    'Unnecessary conditional, value is always falsy.' :
                    'Unnecessary conditional, value is always truthy.',
                results
            );
        }
    }

    private handleIfStatement(condition: ts.Expression, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        if (ts.isPrefixUnaryExpression(condition) && condition.operator === ts.SyntaxKind.ExclamationToken) {
            const operand = condition.operand;
            if (!ts.isLiteralExpression(operand)) {
                return;
            }
            const isAlwaysTruthy = operand.kind === ts.SyntaxKind.TrueKeyword;
            const isAlwaysFalsy = operand.kind === ts.SyntaxKind.FalseKeyword;
            if (isAlwaysTruthy || isAlwaysFalsy) {
                this.recordIssue(condition, sourceFile, results, 'Unnecessary conditional, value is always truthy.');
            }

        } else if (ts.isCallExpression(condition)) {
            // 检查是否是 Promise.resolve() 的调用
            const expression = condition.expression;
            if (ts.isPropertyAccessExpression(expression) &&
                ts.isIdentifier(expression.expression) &&
                expression.expression.text === 'Promise' &&
                ts.isIdentifier(expression.name) &&
                expression.name.text === 'resolve') {
                // 如果是 Promise.resolve()，记录问题
                this.recordIssue(condition, sourceFile, results, 'Unnecessary conditional, value is always truthy.');
            }
        } else {
            if (!ts.isIdentifier(condition)) {
                return;
            }
            const isIdentifierHasNullOrUndefined = this.isIdentifierHasNullOrUndefined(condition, condition.getText(), true);
            if (!isIdentifierHasNullOrUndefined) {
                this.recordIssue(condition, sourceFile, results, 'Unnecessary conditional, value is always truthy.');
            }
        }

    }

    private recordIssue(node: ts.Node, sourceFile: ts.SourceFile, results: LocationInfo[], description: string): void {
        const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
        const assertionName = node.getText();
        const start = node.getStart();
        const end = node.getEnd();
        const endCharacter = character + assertionName.length;
        results.push({
            fileName: sourceFile.fileName,
            line: line + 1,
            startCol: character + 1,
            endCol: endCharacter + 1,
            start: start,
            end: end,
            nameStr: assertionName,
            description: description,
            messageId: 'alwaysTruthy'
        });
    }

    private handleGeneralCondition(condition: ts.Expression, sourceFile: ts.SourceFile, node: ts.Node, results: LocationInfo[]): void {
        if (!this.checkConditionType(sourceFile, node, condition)) {
            return;
        }
        let start: number = 0;
        let end: number = 0;
        let position: ts.LineAndCharacter | undefined;
        let assertionName: string = '';
        let description: string = '';
        if (ts.isBinaryExpression(condition)) {
            const isRightAlwaysFalsy = this.isAlwaysTruthyOrFalsy(condition.right);
            if (isRightAlwaysFalsy) {
                position = sourceFile.getLineAndCharacterOfPosition(condition.right.getStart());
                assertionName = condition.right.getText();
                start = condition.right.getStart();
                end = condition.right.getEnd();
                description = 'Unnecessary conditional, value is always falsy.';
            } else {
                position = sourceFile.getLineAndCharacterOfPosition(condition.left.getStart());
                assertionName = condition.left.getText();
                start = condition.left.getStart();
                end = condition.left.getEnd();
                description = 'Unnecessary conditional, value is always truthy.';

            }
        } else if (ts.isOptionalChain(node)) {
            if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) || ts.isCallExpression(node)) {
                this.checkOptionalChain(node, sourceFile, results);
            }
        } else {
            start = condition.getStart();
            end = condition.getEnd();
            position = sourceFile.getLineAndCharacterOfPosition(condition.getStart());
            assertionName = condition.getText();
            description = 'Unnecessary conditional, value is always truthy.';
        }
        this.pushResults(position, assertionName, sourceFile.fileName, start, end, results, description);
    }
    private pushResults(position: ts.LineAndCharacter | undefined,
        assertionName: string, fileName: string, start: number, end: number,
        results: LocationInfo[], description: string): void {
        if (position) {
            const endCharacter = position.character + assertionName.length;
            results.push({
                fileName: fileName,
                line: position.line + 1,
                startCol: position.character + 1,
                endCol: endCharacter + 1,
                start: start,
                end: end,
                nameStr: assertionName,
                description: description,
                messageId: 'alwaysFalsy'
            });
        }
    }
    private isAlwaysTruthyOrFalsy(expression: ts.Expression): boolean {
        // 检查布尔字面量
        if (expression.kind && (expression.kind === ts.SyntaxKind.TrueKeyword || expression.kind === ts.SyntaxKind.FalseKeyword)) {
            return true;
        }

        // 检查数值字面量
        if (ts.isNumericLiteral(expression)) {
            return expression.text !== '0';
        }

        // 检查字符串字面量
        if (ts.isStringLiteral(expression)) {
            return expression.text !== '';
        }

        // 检查 null 和 undefined
        if (this.isAlwaysNullOrUndefined(expression)) {
            return false;
        }

        // 检查对象字面量
        if (ts.isObjectLiteralExpression(expression)) {
            return true;
        }

        // 检查数组字面量
        if (ts.isArrayLiteralExpression(expression)) {
            return true;
        }

        // 检查函数调用
        if (ts.isCallExpression(expression)) {
            return false; // 函数调用的结果无法确定
        }

        // 检查标识符
        if (ts.isIdentifier(expression)) {
            return false; // 标识符的值无法确定
        }

        // 其他情况默认返回 false
        return false;
    }
    private checkConditionType(sourceFile: ts.SourceFile, node: ts.Node, condition: ts.Expression): boolean {
        // 检查布尔字面量
        if (node.kind && (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword)) {
            return true;
        }
        // 检查二元表达式
        if (this.checkConditionTypeBinaryExpression(sourceFile, node, condition)) {
            return true;
        } else if (ts.isPrefixUnaryExpression(condition)) {
            // 检查一元表达式（如 !a）
            if (condition.operator === ts.SyntaxKind.ExclamationToken) {
                return this.checkConditionType(sourceFile, node, condition.operand);
            }
        } else if (ts.isParenthesizedExpression(condition)) {
            // 检查括号表达式 (a)
            return this.checkConditionType(sourceFile, node, condition.expression);
        } else if (ts.isCallExpression(condition)) {
            // 检查函数调用
            return !this.isCallExpressionHasNullOrUndefined(sourceFile, condition.getText());
        } else if (ts.isIdentifier(condition)) {
            // 检查标识符
            const isIdentifierHasNullOrUndefined = this.isIdentifierHasNullOrUndefined(node, condition.getText());
            return !isIdentifierHasNullOrUndefined;
        } else if (ts.isPropertyAccessExpression(condition)) {
            // 检查属性访问表达式（如 obj.prop）
            return this.checkConditionType(sourceFile, node, condition.expression);
        } else if (ts.isElementAccessExpression(condition)) {
            // 检查元素访问表达式（如 arr[index]）
            return this.checkConditionType(sourceFile, node, condition.expression);
        } else if (this.isExplicitType(condition)) {
            // 检查 this 表达式
            return true;
        } else if (ts.isNonNullExpression(condition)) {
            // 检查非空断言表达式（如 a!）
            return true;
        } else if (ts.isLiteralExpression(condition)) {
            // 检查字面量表达式（如字符串、数字等）
            return true;
        }
        return this.checkConditionTypeStatement(sourceFile, node, condition);
    }

    private checkConditionTypeStatement(sourceFile: ts.SourceFile, node: ts.Node, condition: ts.Expression): boolean {
        // 特殊处理 while (true) 和 for (; true; )
        if (ts.isWhileStatement(node)) {
            if (node.expression.kind === ts.SyntaxKind.TrueKeyword) {
                return true;
            }
        } else if (ts.isForStatement(node)) {
            if (node.condition && node.condition.kind === ts.SyntaxKind.TrueKeyword) {
                return true;
            }
        } else if (ts.isDoStatement(node)) {
            if (node.expression && node.expression.kind === ts.SyntaxKind.TrueKeyword) {
                return true;
            }
        }
        // 如果以上都不是，返回 false
        return false;
    }

    private checkConditionTypeBinaryExpression(sourceFile: ts.SourceFile, node: ts.Node, condition: ts.Expression): boolean {
        // 检查二元表达式
        if (ts.isBinaryExpression(condition)) {
            const left = condition.left;
            const right = condition.right;

            if (condition.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken) {
                // && 操作符
                const isLeftAlwaysFalsy = this.checkConditionType(sourceFile, node, left);
                const isRightAlwaysFalsy = this.checkConditionType(sourceFile, node, right);

                if (isLeftAlwaysFalsy || isRightAlwaysFalsy) {
                    return true;
                }
            } else if (condition.operatorToken.kind === ts.SyntaxKind.BarBarToken) {
                // || 操作符
                const isLeftAlwaysTruthy = this.checkConditionType(sourceFile, node, left);
                const isRightAlwaysTruthy = this.checkConditionType(sourceFile, node, right);

                if (isLeftAlwaysTruthy || isRightAlwaysTruthy) {
                    return true;
                }
            } else {
                // 检查是否比较 undefined 或 null
                const isUndefinedComparison = this.isAlwaysNullOrUndefined(left) || this.isAlwaysNullOrUndefined(right);
                const isNullComparison = this.isAlwaysNullOrUndefined(left) || this.isAlwaysNullOrUndefined(right);

                // 检查另一侧是否为明确的类型（如 string、number 等）
                const isExplicitType = this.isExplicitType(left) || this.isExplicitType(right);

                if ((isUndefinedComparison || isNullComparison) && isExplicitType) {
                    return true;
                }
            }
        }
        // 如果以上都不是，返回 false
        return false;
    }

    private isExplicitType(node: ts.Node): boolean {
        if (ts.isStringLiteral(node) || ts.isNumericLiteral(node)) {
            return true;
        }
        return false;
    }

    private isCallExpressionHasNullOrUndefined(sourceFile: ts.SourceFile, identifier: string): boolean {
        for (let stmtNode of sourceFile?.statements ?? []) {
            if (!ts.isVariableStatement(stmtNode)) {
                continue;
            }
            let variableList = stmtNode.declarationList;
            if (!variableList || !variableList.declarations) {
                continue;
            }
            for (let declaration of variableList.declarations) {
                if (!ts.isVariableDeclaration(declaration)) {
                    continue;
                }
                let nameIdentifier = declaration.name;
                if (!ts.isIdentifier(nameIdentifier) || !(nameIdentifier.escapedText === identifier)) {
                    continue;
                }
                if (declaration.initializer?.getText().includes('null') || declaration.initializer?.getText().includes('undefined')) {
                    return true;
                }
            }
        }
        return false;
    }

    private isIdentifierHasNullOrUndefined(node: ts.Node, identifier: string, isIf?: boolean): boolean {

        // 遍历父节点语句
        let parentNode = node.parent;
        while (parentNode) {
            // 递归检查每个语句节点
            if (this.checkNodeC(parentNode, identifier, isIf)) {
                return true;
            }
            parentNode = parentNode.parent;
        }
        return false;
    }
    private checkNodeC(node: ts.Node, identifier: string, isIf?: boolean): boolean {
        // 如果当前节点是变量声明
        if (ts.isVariableStatement(node) && this.checkNodeVariableStatement(node, identifier)) {
            return true;
        }
        // 如果当前节点是函数声明或方法声明
        if (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) {
            const parameters = node.parameters;
            for (let i = 0; i < parameters.length; i++) {
                if (this.checkNodeFunction(i, parameters, identifier, isIf)) {
                    return true;
                }
            }
        }
        // 如果当前节点是表达式语句
        else if (ts.isExpressionStatement(node)) {
            if (this.isNullOrUndefined(node.expression)) {
                return true;
            }
        }
        // 如果当前节点是赋值表达式
        else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
            if (this.checkNodeIdentifier(node, identifier)) {
                return true;
            }
        }
        // 递归检查子节点
        for (const child of node.getChildren()) {
            this.checkNodeC(child, identifier, isIf);
        }
        return false;
    }

    private checkNodeVariableStatement(node: ts.VariableStatement, identifier: string): boolean {
        for (const declaration of node.declarationList.declarations) {
            // 检查变量名是否匹配
            if (ts.isIdentifier(declaration.name) && declaration.name.text === identifier) {
                // 检查初始化值是否为 null 或 undefined
                if (declaration.initializer && this.isNullOrUndefined(declaration.initializer)) {
                    return true;
                }
            }
        }
        return false;
    }
    private checkNodeFunction(i: number, parameters: ts.NodeArray<ts.ParameterDeclaration>, identifier: string, isIf?: boolean): boolean {
        const parameter = parameters[i];
        if (parameter.name.getText() === identifier) {
            if (parameter.type) {
                const parameterType = parameter.type?.getText()?.toString();
                if (isIf && (parameterType === 'number' || parameterType === 'string' || parameterType === 'boolean' || parameterType === 'any')) {
                    return true;
                }
                if (!parameterType || parameterType.includes('null') || parameterType.includes('undefined')) {
                    return true;
                }
            }
        }
        return false;
    }

    private checkNodeIdentifier(node: ts.BinaryExpression, identifier: string): boolean {
        // 检查赋值的左侧是否为目标标识符
        if (ts.isIdentifier(node.left) && node.left.text === identifier) {
            // 检查赋值的右侧是否为 null 或 undefined
            if (this.isNullOrUndefined(node.right)) {
                return true;
            }
        }
        return false;
    }

    private isNullOrUndefined(node: ts.Node): boolean {
        // 检查节点是否为 null 或 undefined
        return (ts.isIdentifier(node) && (node.text.includes('null') || node.text.includes('undefined')));
    }

    private handleCallExpression(node: ts.CallExpression, sourceFile: ts.SourceFile, results: LocationInfo[]): ts.Expression | undefined {
        const expression = node.expression;
        const args = node.arguments;
        const arrayPredicate = new Set(['filter', 'find', 'some', 'every']);
        if (ts.isPropertyAccessExpression(expression) && arrayPredicate.has(expression.name.text)) {
            const callback = args[0];
            if (callback && ts.isArrowFunction(callback) && ts.isIdentifier(callback.body)) {
                this.handleGeneralCondition(callback.body, sourceFile, node, results);
                return callback.body;
            }
        }
        return undefined;
    }

    private handleBinaryExpression(node: ts.BinaryExpression, sourceFile: ts.SourceFile, results: LocationInfo[], options: Options): ts.Expression | undefined {
        if (node.operatorToken.kind === ts.SyntaxKind.QuestionQuestionEqualsToken || node.operatorToken.kind === ts.SyntaxKind.BarBarEqualsToken ||
            node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandEqualsToken || node.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken) {
            // 检查左侧操作数是否总是为 null 或 undefined
            const isLeftAlwaysNullOrUndefined = this.isAlwaysNullOrUndefined(node.left);
            if (!isLeftAlwaysNullOrUndefined || (node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandEqualsToken && isLeftAlwaysNullOrUndefined)) {
                const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.left.getStart());
                const assertionName = node.left.getText();
                const start = node.left.getStart();
                const end = node.left.getEnd();
                const endCharacter = character + assertionName.length;

                results.push({
                    fileName: sourceFile.fileName,
                    line: line + 1,
                    startCol: character + 1,
                    endCol: endCharacter + 1,
                    start: start,
                    end: end,
                    nameStr: assertionName,
                    description: 'Unnecessary optional chain on a non-nullish value.',
                    messageId: 'alwaysFalsy'
                });
            }
            return undefined;
        } else {
            this.handleGeneralCondition(node, sourceFile, node, results);
            return node;
        }
    }

    private isAlwaysNullOrUndefined(node: ts.Node): boolean {
        // 检查是否为 null 字面量
        if (node.kind === ts.SyntaxKind.NullKeyword) {
            return true;
        }

        // 检查是否为 undefined 字面量
        if (ts.isIdentifier(node) && node.text === 'undefined') {
            return true;
        }

        // 检查是否为布尔字面量 false（在某些情况下可能被视为 'falsy'）
        if (ts.isLiteralExpression(node) &&
            (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword)) {
            return true;
        }

        // 检查是否为标识符
        if (ts.isIdentifier(node)) {
            return this.isIdentifierAlwaysNullOrUndefined(node);
        }

        // 检查是否为二元表达式
        if (ts.isBinaryExpression(node)) {
            // 递归检查二元表达式的操作数
            return this.isAlwaysNullOrUndefined(node.left) && this.isAlwaysNullOrUndefined(node.right);
        }

        // 其他情况默认返回 false
        return false;
    }
    private isIdentifierAlwaysNullOrUndefined(identifier: ts.Identifier): boolean {
        return identifier.text === 'null' || identifier.text === 'undefined';
    }
    // 检查节点是否总是为真或总是为假
    private checkNode(node: ts.Expression, sourceFile: ts.SourceFile, results: LocationInfo[],
        isUnaryNotArgument: boolean = false): void {
        this.checkPromiseCondition(node, sourceFile, results);
        // 处理一元取反运算符 (!)
        if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.ExclamationToken) {
            this.checkNode(node.operand, sourceFile, results, true);
        }

        // 处理布尔字面量
        if (ts.isLiteralExpression(node)) {
            if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword) {
                const alwaysTruthy = node.kind === ts.SyntaxKind.TrueKeyword;
                const messageId = !isUnaryNotArgument ?
                    (alwaysTruthy ? 'alwaysTruthy' : 'alwaysFalsy') :
                    (alwaysTruthy ? 'alwaysFalsy' : 'alwaysTruthy');

                const description = !isUnaryNotArgument ?
                    (alwaysTruthy ? 'Unnecessary conditional, value is always truthy.' : 'Unnecessary conditional, value is always falsy.') :
                    (alwaysTruthy ? 'Unnecessary conditional, value is always falsy.' : 'Unnecessary conditional, value is always truthy.');

                this.reportIssue(node, sourceFile, messageId, description, results);
                return;
            }
        }
        // 处理布尔字面量
        if (node.kind === ts.SyntaxKind.TrueKeyword || node.kind === ts.SyntaxKind.FalseKeyword) {
            const alwaysTruthy = node.kind === ts.SyntaxKind.TrueKeyword;
            const messageId = !isUnaryNotArgument ?
                (alwaysTruthy ? 'alwaysTruthy' : 'alwaysFalsy') :
                (alwaysTruthy ? 'alwaysFalsy' : 'alwaysTruthy');

            const description = !isUnaryNotArgument ?
                (alwaysTruthy ? 'Unnecessary conditional, value is always truthy.' : 'Unnecessary conditional, value is always falsy.') :
                (alwaysTruthy ? 'Unnecessary conditional, value is always falsy.' : 'Unnecessary conditional, value is always truthy.');

            this.reportIssue(node, sourceFile, messageId, description, results);
            return;
        }
        this.checkNodeTwo(node, sourceFile, results, isUnaryNotArgument);
    }

    private checkNodeTwo(node: ts.Expression, sourceFile: ts.SourceFile, results: LocationInfo[],
        isUnaryNotArgument: boolean): void {
        if (ts.isNewExpression(node)) {
            this.reportIssue(
                node,
                sourceFile,
                'noOverlapBooleanExpression',
                'Unnecessary conditional, the types have no overlap.',
                results
            );
            return;
        }
        // 检查数值字面量
        if (ts.isNumericLiteral(node)) {
            const isZero = node.text === '0';
            const messageId = !isUnaryNotArgument ?
                (isZero ? 'alwaysFalsy' : 'alwaysTruthy') :
                (isZero ? 'alwaysTruthy' : 'alwaysFalsy');

            const description = !isUnaryNotArgument ?
                (isZero ? 'Unnecessary conditional, value is always falsy.' : 'Unnecessary conditional, value is always truthy.') :
                (isZero ? 'Unnecessary conditional, value is always truthy.' : 'Unnecessary conditional, value is always falsy.');

            this.reportIssue(node, sourceFile, messageId, description, results);
            return;
        }

        // 检查字符串字面量
        if (ts.isStringLiteral(node)) {
            const isEmpty = node.text === '';
            const messageId = !isUnaryNotArgument ?
                (isEmpty ? 'alwaysFalsy' : 'alwaysTruthy') :
                (isEmpty ? 'alwaysTruthy' : 'alwaysFalsy');

            const description = !isUnaryNotArgument ?
                (isEmpty ? 'Unnecessary conditional, value is always falsy.' : 'Unnecessary conditional, value is always truthy.') :
                (isEmpty ? 'Unnecessary conditional, value is always truthy.' : 'Unnecessary conditional, value is always falsy.');

            this.reportIssue(node, sourceFile, messageId, description, results);
            return;
        }

        this.checkNodeOther(node, sourceFile, results, isUnaryNotArgument);
    }

    private checkNodeOther(node: ts.Expression, sourceFile: ts.SourceFile, results: LocationInfo[],
        isUnaryNotArgument: boolean): void {
        // 处理特殊逻辑表达式
        if (ts.isBinaryExpression(node)) {
            // 检查逻辑表达式，如 && 和 || 操作符
            if (node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken) {
                // 检查 && 操作符左侧
                this.checkNode(node.left, sourceFile, results, false);
                return;
            } else if (node.operatorToken.kind === ts.SyntaxKind.BarBarToken) {
                // 检查 || 操作符左侧
                this.checkNode(node.left, sourceFile, results, false);
                return;
            } else if (node.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken) {
                // 检查 ?? 操作符左侧是否可能为 null 或 undefined
                this.checkNodeForNullish(node.left, sourceFile, results);
                return;
            }

            // 检查比较表达式，如 === 和 !==
            const boolOperators = [ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken,
                ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken,
                ts.SyntaxKind.ExclamationEqualsEqualsToken];

            if (boolOperators.includes(node.operatorToken.kind)) {
                this.checkBinaryExpression(node, sourceFile, results);
            }
        }

        // 检查对象字面量和数组字面量
        if (ts.isObjectLiteralExpression(node) || ts.isArrayLiteralExpression(node)) {
            const messageId = !isUnaryNotArgument ? 'alwaysTruthy' : 'alwaysFalsy';
            const description = !isUnaryNotArgument ?
                'Unnecessary conditional, value is always truthy.' :
                'Unnecessary conditional, value is always falsy.';

            this.reportIssue(node, sourceFile, messageId, description, results);
            return;
        }

        // 检查 null 和 undefined
        if (node.kind === ts.SyntaxKind.NullKeyword ||
            (ts.isIdentifier(node) && node.text === 'undefined')) {
            const messageId = !isUnaryNotArgument ? 'alwaysFalsy' : 'alwaysTruthy';
            const description = !isUnaryNotArgument ?
                'Unnecessary conditional, value is always falsy.' :
                'Unnecessary conditional, value is always truthy.';

            this.reportIssue(node, sourceFile, messageId, description, results);
            return;
        }
    }

    private checkPromiseCondition(condition: ts.Expression, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        // 特别检查 Promise.resolve() 调用
        if (ts.isCallExpression(condition)) {
            const expression = condition.expression;
            if (ts.isPropertyAccessExpression(expression) &&
                ts.isIdentifier(expression.expression) &&
                expression.expression.text === 'Promise' &&
                ts.isIdentifier(expression.name) &&
                expression.name.text === 'resolve') {

                this.reportIssue(
                    condition,
                    sourceFile,
                    'alwaysTruthy',
                    'Unnecessary conditional, value is always truthy.',
                    results
                );
            }
        }
    }

    // 检查可选链
    private checkOptionalChain(
        node: ts.PropertyAccessExpression | ts.ElementAccessExpression | ts.CallExpression,
        sourceFile: ts.SourceFile,
        results: LocationInfo[]
    ): void {
        // 检查可选链操作符是否必要
        if (node.questionDotToken) {

            const questionDotToken = node.questionDotToken;
            this.reportIssue(
                questionDotToken,
                sourceFile,
                'neverOptionalChain',
                'Unnecessary optional chain on a non-nullish value.',
                results
            );
        }
    }

    // 检查二元表达式
    private checkBinaryExpression(node: ts.BinaryExpression, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        // 处理比较操作符
        const boolOperators = [ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken,
        ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken,
        ts.SyntaxKind.ExclamationEqualsEqualsToken];
        if (boolOperators.includes(node.operatorToken.kind)) {
            // 检查变量与字面量的比较
            if (ts.isIdentifier(node.left) && (ts.isNumericLiteral(node.right) || ts.isStringLiteral(node.right) || ts.isLiteralExpression(node.right))) {
                // 左侧是标识符，右侧是字面量
                const identifier = node.left;
                const literal = node.right;

                // 检查未初始化变量与已知值的比较
                if (this.isUninitializedVariable(identifier, sourceFile)) {
                    this.reportIssue(node, sourceFile, 'alwaysFalsy',
                        'Unnecessary conditional, both sides of the expression are literal values.', results);
                    return;
                }
                // 检查已知值与相同值的比较
                else if (this.isVariableWithKnownValue(identifier, literal, sourceFile)) {
                    const isEqualityCheck = node.operatorToken.kind === ts.SyntaxKind.EqualsEqualsToken ||
                        node.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken;

                    this.reportIssue(node, sourceFile, isEqualityCheck ? 'alwaysTruthy' : 'alwaysFalsy',
                        'Unnecessary conditional, both sides of the expression are literal values.', results);
                    return;
                }
            } else if (ts.isIdentifier(node.right) && (ts.isNumericLiteral(node.left) || ts.isStringLiteral(node.left) || ts.isLiteralExpression(node.left))) {
                // 右侧是标识符，左侧是字面量
                const identifier = node.right;
                const literal = node.left;

                // 检查未初始化变量与已知值的比较
                if (this.isUninitializedVariable(identifier, sourceFile)) {
                    this.reportIssue(node, sourceFile, 'alwaysFalsy',
                        'Unnecessary conditional, both sides of the expression are literal values.', results);
                    return;
                }
                // 检查已知值与相同值的比较
                else if (this.isVariableWithKnownValue(identifier, literal, sourceFile)) {
                    const isEqualityCheck = node.operatorToken.kind === ts.SyntaxKind.EqualsEqualsToken ||
                        node.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken;

                    this.reportIssue(node, sourceFile, isEqualityCheck ? 'alwaysTruthy' : 'alwaysFalsy',
                        'Unnecessary conditional, both sides of the expression are literal values.', results);
                    return;
                }
            }
            this.checkBinaryExpressionOne(node, sourceFile, results);
        }
    }

    private checkBinaryExpressionOne(node: ts.BinaryExpression, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        // 先检查等值表达式的特殊情况: true === true, false === false, true === false, false === true
        if ((node.operatorToken.kind === ts.SyntaxKind.EqualsEqualsToken ||
            node.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken ||
            node.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsToken ||
            node.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken)) {

            // 检查布尔字面量与 null 的比较
            const isLeftNull = node.left.kind === ts.SyntaxKind.NullKeyword;
            const isRightNull = node.right.kind === ts.SyntaxKind.NullKeyword;
            const isLeftBoolean = node.left.kind === ts.SyntaxKind.TrueKeyword || node.left.kind === ts.SyntaxKind.FalseKeyword;
            const isRightBoolean = node.right.kind === ts.SyntaxKind.TrueKeyword || node.right.kind === ts.SyntaxKind.FalseKeyword;

            // 布尔值与 null 比较
            if ((isLeftBoolean && isRightNull) || (isLeftNull && isRightBoolean)) {
                this.reportIssue(node, sourceFile, 'noOverlapBooleanExpression',
                    'Unnecessary conditional, boolean literals will never be equal to null.', results);
                return;
            }

            // 获取左右操作数的布尔值
            const isLeftTrue = node.left.kind === ts.SyntaxKind.TrueKeyword;
            const isRightTrue = node.right.kind === ts.SyntaxKind.TrueKeyword;
            const isLeftFalse = node.left.kind === ts.SyntaxKind.FalseKeyword;
            const isRightFalse = node.right.kind === ts.SyntaxKind.FalseKeyword;

            // 判断是否是布尔字面量之间的比较
            if ((isLeftTrue || isLeftFalse) && (isRightTrue || isRightFalse)) {
                this.reportIssue(node, sourceFile, 'literalBooleanExpression',
                    'Unnecessary conditional, both sides of the expression are literal values.', results);
                return;
            }
        }
        this.checkBinaryExpressionTwo(node, sourceFile, results);
    }
    private checkBinaryExpressionTwo(node: ts.BinaryExpression, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        // 获取去除括号后的左右操作数
        const leftWithoutParens = this.unwrapParenthesizedExpression(node.left);
        const rightWithoutParens = this.unwrapParenthesizedExpression(node.right);

        // 检查两侧是否都是字面量类型
        const isLeftLiteral = ts.isLiteralExpression(leftWithoutParens) ||
            ts.isStringLiteral(leftWithoutParens) ||
            ts.isNumericLiteral(leftWithoutParens) ||
            leftWithoutParens.kind === ts.SyntaxKind.NullKeyword ||
            (ts.isIdentifier(leftWithoutParens) && leftWithoutParens.text === 'undefined');

        const isRightLiteral = ts.isLiteralExpression(rightWithoutParens) ||
            ts.isStringLiteral(rightWithoutParens) ||
            ts.isNumericLiteral(rightWithoutParens) ||
            rightWithoutParens.kind === ts.SyntaxKind.NullKeyword ||
            (ts.isIdentifier(rightWithoutParens) && rightWithoutParens.text === 'undefined');

        if (isLeftLiteral && isRightLiteral) {
            this.reportIssue(node, sourceFile, 'literalBooleanExpression',
                'Unnecessary conditional, both sides of the expression are literal values.', results);
            return;
        }
        // 检查是否是 null/undefined 与不兼容类型比较
        const isLeftNullish =
            leftWithoutParens.kind === ts.SyntaxKind.NullKeyword ||
            (ts.isIdentifier(leftWithoutParens) && leftWithoutParens.text === 'undefined');

        const isRightNullish =
            rightWithoutParens.kind === ts.SyntaxKind.NullKeyword ||
            (ts.isIdentifier(rightWithoutParens) && rightWithoutParens.text === 'undefined');

        const isStrictEquality =
            node.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken ||
            node.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken;

        // 检查严格相等比较
        if (isStrictEquality && (isLeftNullish || isRightNullish)) {
            const otherSide = isLeftNullish ? rightWithoutParens : leftWithoutParens;
            this.checkBinaryExpressionOtherOne(otherSide, node, sourceFile, results);
        }

        // 检查非严格相等比较中的特殊情况
        if (!isStrictEquality && (isLeftNullish || isRightNullish)) {
            const otherSide = isLeftNullish ? rightWithoutParens : leftWithoutParens;
            this.checkBinaryExpressionOtherTwo(otherSide, node, sourceFile, results);
        }
    }

    private checkBinaryExpressionOtherOne(otherSide: ts.Expression, node: ts.BinaryExpression, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        // 如果另一侧是字面量且不是 null/undefined，那么这个比较没有意义
        if ((ts.isStringLiteral(otherSide) ||
            ts.isNumericLiteral(otherSide) ||
            ts.isLiteralExpression(otherSide) &&
            (otherSide.kind === ts.SyntaxKind.TrueKeyword ||
                otherSide.kind === ts.SyntaxKind.FalseKeyword)) &&
            otherSide.kind !== ts.SyntaxKind.NullKeyword &&
            !(ts.isIdentifier(otherSide) && otherSide.text === 'undefined')) {

            this.reportIssue(node, sourceFile, 'noOverlapBooleanExpression',
                'Unnecessary conditional, the types have no overlap.', results);
            return;
        }
    }
    private checkBinaryExpressionOtherTwo(otherSide: ts.Expression, node: ts.BinaryExpression, sourceFile: ts.SourceFile, results: LocationInfo[]): void {
        // 特别检查布尔字面量与 null 的非严格比较
        if (otherSide.kind === ts.SyntaxKind.TrueKeyword || otherSide.kind === ts.SyntaxKind.FalseKeyword) {
            const compareOp = node.operatorToken.kind === ts.SyntaxKind.EqualsEqualsToken ? '==' : '!=';
            this.reportIssue(node, sourceFile, 'noOverlapBooleanExpression',
                `Unnecessary conditional, boolean ${compareOp} null is always ${compareOp === '==' ? 'false' : 'true'}.`,
                results);
            return;
        }
    }

    // 修改 unwrapParenthesizedExpression 方法以确保它可以处理嵌套括号
    private unwrapParenthesizedExpression(node: ts.Expression): ts.Expression {
        // 递归处理嵌套括号表达式，直到找到非括号表达式
        if (ts.isParenthesizedExpression(node)) {
            return this.unwrapParenthesizedExpression(node.expression);
        }
        return node;
    }

    // 检查节点是否为 nullish 值（用于 ?? 操作符）
    private checkNodeForNullish(
        node: ts.Expression,
        sourceFile: ts.SourceFile,
        results: LocationInfo[]
    ): void {
        // 检查是否始终为 null 或 undefined
        if (node.kind === ts.SyntaxKind.NullKeyword ||
            (ts.isIdentifier(node) && node.text === 'undefined')) {
            this.reportIssue(
                node,
                sourceFile,
                'alwaysNullish',
                'Unnecessary conditional, left-hand side of `??` operator is always `null` or `undefined`.',
                results
            );
            return;
        }

        // 检查是否永远不可能为 null 或 undefined
        if (ts.isObjectLiteralExpression(node) ||
            ts.isArrayLiteralExpression(node) ||
            ts.isLiteralExpression(node) && node.kind === ts.SyntaxKind.TrueKeyword ||
            ts.isLiteralExpression(node) && node.kind === ts.SyntaxKind.FalseKeyword ||
            ts.isNumericLiteral(node) ||
            ts.isStringLiteral(node)) {

            this.reportIssue(
                node,
                sourceFile,
                'neverNullish',
                'Unnecessary conditional, expected left-hand side of `??` operator to be possibly null or undefined.',
                results
            );
            return;
        }
    }

    // 辅助方法：创建和添加问题报告
    private reportIssue(
        node: ts.Node,
        sourceFile: ts.SourceFile,
        messageId: MessageId,
        description: string,
        results: LocationInfo[]
    ): void {
        const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());
        const assertionName = node.getText();
        const start = node.getStart();
        const end = node.getEnd();
        const endCharacter = character + assertionName.length;

        results.push({
            fileName: sourceFile.fileName,
            line: line + 1,
            startCol: character + 1,
            endCol: endCharacter + 1,
            start: start,
            end: end,
            nameStr: assertionName,
            description: description,
            messageId: messageId
        });
    }

    // 创建修复对象 
    private ruleFix(loc: LocationInfo): RuleFix {
        const [start, end] = this.getFixRange(loc);
        return { range: [start, end], text: '.' };
    }

    // 获取起始位置和结束位置
    private getFixRange(loc: LocationInfo): [number, number] {
        const startPosition = loc.start;
        const endPosition = loc.end;
        return [startPosition, endPosition];
    }

    private addIssueReportNodeFix(loc: LocationInfo, filePath: string): void {
        const severity = this.rule.alert ?? this.metaData.severity;
        if (loc.description) {
            this.metaData.description = loc.description;
        }
        if (loc.nameStr === '?.') {
            let defectFix = new Defects(loc.line, loc.startCol, loc.endCol, this.metaData.description, severity,
                this.rule.ruleId, filePath, this.metaData.ruleDocPath, true, false, true);
            let fix: RuleFix = this.ruleFix(loc);
            this.issues.push(new IssueReport(defectFix, fix));
            RuleListUtil.push(defectFix);
        } else {
            let defect = new Defects(loc.line, loc.startCol, loc.endCol, this.metaData.description, severity,
                this.rule.ruleId, filePath, this.metaData.ruleDocPath, true, false, false);
            this.issues.push(new IssueReport(defect, undefined));
            RuleListUtil.push(defect);
        }
    }

    // 检查变量是否未初始化
    private isUninitializedVariable(identifier: ts.Identifier, sourceFile: ts.SourceFile): boolean {
        // 先检查整个源文件中是否有此变量的定义
        const variableName = identifier.text;

        // 遍历整个源文件的语句
        const checkStatements = (statements: ts.NodeArray<ts.Statement>): boolean => {
            return this.isUninitializedVariableStatements(statements, variableName);
        };
        return checkStatements(sourceFile.statements);
    }

    private isUninitializedVariableStatements(statements: ts.NodeArray<ts.Statement>, variableName: string): boolean {
        for (const statement of statements) {
            // 检查变量声明语句
            if (ts.isVariableStatement(statement)) {
                return this.isUninitializedVariableStatement(statement, variableName);
            }
        }
        return false;
    }

    private isUninitializedVariableStatement(statement: ts.VariableStatement, variableName: string): boolean {
        let foundDeclaration = false;
        let isUninitialized = false;
        const declarations = statement.declarationList.declarations;
        for (const declaration of declarations) {
            if (ts.isIdentifier(declaration.name) && declaration.name.text === variableName) {
                foundDeclaration = true;
                // 检查是否有初始化表达式
                if (!declaration.initializer) {
                    isUninitialized = true;
                    // 没有初始化，直接返回
                    return foundDeclaration && isUninitialized;
                }
            }
        }
        return foundDeclaration && isUninitialized;
    }

    // 检查变量是否具有已知的值，并且正在与该值进行比较
    private isVariableWithKnownValue(identifier: ts.Identifier, comparedValue: ts.Expression, sourceFile: ts.SourceFile): boolean {
        // 先确保比较值是我们能处理的类型
        let literalValue: string | number | boolean | null | undefined;

        if (ts.isNumericLiteral(comparedValue)) {
            literalValue = Number(comparedValue.text);
        } else if (ts.isStringLiteral(comparedValue)) {
            literalValue = comparedValue.text;
        } else if (comparedValue.kind === ts.SyntaxKind.TrueKeyword) {
            literalValue = true;
        } else if (comparedValue.kind === ts.SyntaxKind.FalseKeyword) {
            literalValue = false;
        } else if (comparedValue.kind === ts.SyntaxKind.NullKeyword) {
            literalValue = null;
        } else if (ts.isIdentifier(comparedValue) && comparedValue.text === 'undefined') {
            literalValue = undefined;
        } else {
            return false; // 不是我们能处理的字面量类型
        }

        // 获取变量名
        const variableName = identifier.text;
        let foundDeclaration = false;
        let hasMatchingValue = false;



        // 遍历所有语句，包括顶层声明和块级作用域
        const findVariableDeclarations = (node: ts.Node): void => {
            // 如果已经找到匹配的声明和值，不再继续搜索
            if (hasMatchingValue) {
                return;
            }

            // 检查变量声明
            if (ts.isVariableDeclaration(node) &&
                ts.isIdentifier(node.name) &&
                node.name.text === variableName &&
                node.initializer) {

                foundDeclaration = true;

                // 检查初始化值
                if (this.hasMatchingLiteralValue(node.initializer, literalValue)) {
                    hasMatchingValue = true;
                    return;
                }
            }

            // 检查赋值表达式 (x = value)
            if (ts.isBinaryExpression(node) &&
                node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
                ts.isIdentifier(node.left) &&
                node.left.text === variableName) {

                foundDeclaration = true;

                // 检查赋值的右侧
                if (this.hasMatchingLiteralValue(node.right, literalValue)) {
                    hasMatchingValue = true;
                    return;
                }
            }

            // 递归检查子节点
            node.forEachChild(findVariableDeclarations);
        };

        // 从源文件开始搜索
        findVariableDeclarations(sourceFile);

        return foundDeclaration && hasMatchingValue;
    }

    // 检查表达式是否匹配特定的字面量值
    private hasMatchingLiteralValue(expression: ts.Expression, value: string | number | boolean | null | undefined): boolean {
        // 对于括号表达式，检查内部表达式
        if (ts.isParenthesizedExpression(expression)) {
            return this.hasMatchingLiteralValue(expression.expression, value);
        }

        // 检查各种字面量类型
        if (value === null && expression.kind === ts.SyntaxKind.NullKeyword) {
            return true;
        }
        if (value === undefined && ts.isIdentifier(expression) && expression.text === 'undefined') {
            return true;
        }
        if (ts.isNumericLiteral(expression) && typeof value === 'number') {
            const numValue = Number(expression.text);
            return numValue === value;
        }
        if (ts.isStringLiteral(expression) && typeof value === 'string') {
            return expression.text === value;
        }
        if (expression.kind === ts.SyntaxKind.TrueKeyword && value === true) {
            return true;
        }
        if (expression.kind === ts.SyntaxKind.FalseKeyword && value === false) {
            return true;
        }

        // 对于括号表达式，检查内部表达式
        if (ts.isParenthesizedExpression(expression)) {
            return this.hasMatchingLiteralValue(expression.expression, value);
        }

        return false;
    }

    // 修改 isAlwaysFalsyValue 方法以确保递归处理括号表达式
    private isAlwaysFalsyValue(expression: ts.Expression): boolean {
        // 处理括号表达式，递归解析内部表达式
        if (ts.isParenthesizedExpression(expression)) {
            return this.isAlwaysFalsyValue(expression.expression);
        }

        // 检查数值字面量 0
        if (ts.isNumericLiteral(expression)) {
            return Number(expression.text) === 0;
        }

        // 检查空字符串
        if (ts.isStringLiteral(expression)) {
            return expression.text === '';
        }

        // 检查 false 字面量
        if (expression.kind === ts.SyntaxKind.FalseKeyword) {
            return true;
        }

        // 检查 null 和 undefined
        if (expression.kind === ts.SyntaxKind.NullKeyword ||
            (ts.isIdentifier(expression) && expression.text === 'undefined')) {
            return true;
        }

        // 检查基本的前缀表达式
        if (ts.isPrefixUnaryExpression(expression)) {
            // void 表达式总是返回 undefined
            if (expression.getText().startsWith('void ')) {
                return true;
            }
        }

        // 检查 NaN
        if (ts.isIdentifier(expression) && expression.text === 'NaN') {
            return true;
        }

        // 其他情况，视为真值
        return false;
    }
}